# -*- coding: utf-8 -*-
from xlwt import Workbook
import os
import shutil
import threading

g_lock = threading.Lock()


def w_xls(data):
    try:
        val = data["v"]

        p = data["p"]
        path = "/files/%s.xls" % p

        dir = os.path.dirname(path)
        if os.path.exists(dir):
            shutil.rmtree(dir)

        os.makedirs(dir)

        wb = Workbook()
        sheet = wb.add_sheet("Sheet1")

        for r, row in enumerate(val):
            for c, col in enumerate(row):
                sheet.write(r, c, "%s" % col)

        wb.save(path)

        return None
    except Exception as e:
        return e


def do_write(data):
    with g_lock:
        w_xls(data)
